package dk.ahp.getmeoff;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;
import android.util.Log;

/**
 * Denne klasse håndtere læsning, skrivning og opdatering af Destiantioner fra database. 
 */
public class DBHelper extends SQLiteOpenHelper {
	private static final String TAG = DBHelper.class.getSimpleName();
	private static final int dbVersion = 6;
	
	public DBHelper(Context context, String dbName) {
		super(context, dbName, null, dbVersion);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// Oprette tabel
		// db version 2
		// db.execSQL("CREATE TABLE destinations (_id INTEGER PRIMARY KEY AUTOINCREMENT, navn TEXT NOT NULL, " +
		//		"part TEXT, startLat REAL, startLon REAL, destLat REAL, destLon REAL);");

		// db version 5
		db.execSQL("CREATE TABLE destinations (_id INTEGER PRIMARY KEY AUTOINCREMENT, navn TEXT NOT NULL, " +
				"startLat REAL, startLon REAL, destLat REAL, destLon REAL, destAddress TEXT, startAddress TEXT);");

		Log.d(TAG, "onCreate: table created");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.d(TAG, "onUpgrade: update db");
		// db version 2 
		// db.execSQL("drop table if exists destinations");
		// onCreate(db);

		// db version 4
		// db.execSQL("alter table destinations add column destAddress TEXT");
		// db.execSQL("alter table destinations add column endAddress TEXT");
		
		// db version 6
		db.execSQL("drop table if exists destinations");
		onCreate(db);
	}

	/**
	 * Læser alle destiantioner fra database og opretter Destination objekter.
	 * 
	 * @return Liste af destiantions læst fra databasen.
	 */
	public List<Destination> getAllDestinations() {
		SQLiteDatabase db = getReadableDatabase();
		List<Destination> destinations = new ArrayList<Destination>();

		Cursor cursor = null;
		String[] kolonner = {"_id", "navn", "startLat", "startLon", "destLat", "destLon", "destAddress", "startAddress"};
		try {
			cursor = db.query("destinations", kolonner, null, null, null, null, null);
			while (cursor.moveToNext()) {
				long id = cursor.getLong(0);
				String navn = cursor.getString(1);
				float startLat = cursor.getFloat(2);
				float startLon = cursor.getFloat(3);
				float destLat = cursor.getFloat(4);
				float destLon = cursor.getFloat(5);
				String destAddress = cursor.getString(6);
				String startAddress = cursor.getString(7);
				
				Location destination = new Location("Destination");
				destination.setLatitude(destLat);
				destination.setLongitude(destLon);
				Location start = new Location("Start");
				start.setLatitude(startLat);
				start.setLongitude(startLon);
				Destination dest = new Destination(navn, destination, start, id, startAddress, destAddress);
				destinations.add(dest);
			}

		} finally {
			if(null != cursor) {
				cursor.close();
			}
			db.close();
		}
		Log.d(TAG, "DestinationLogic created");

		return destinations;
	}

	/**
	 * @param dest Destiantion som skal gemmes.
	 * @return True hvis dest blev tilføjet databasen. 
	 */
	public Boolean AddDestination(Destination dest) {
		ContentValues row = new ContentValues();
		row.put("navn", dest.getName());
		
		if(null !=  dest.getStart()) {
			row.put("startLat", dest.getStart().getLatitude());
			row.put("startLon", dest.getStart().getLongitude());
		}

		if (null != dest.getDestination()) {
			row.put("destLat", dest.getDestination().getLatitude());
			row.put("destLon", dest.getDestination().getLongitude());
		}

		if (null != dest.getDestAddress() || !"".equals(dest.getDestAddress())) {
			row.put("destAddress", dest.getDestAddress());
		}
		
		if (null != dest.getStartAddress() || !"".equals(dest.getStartAddress())) {
			row.put("startAddress", dest.getStartAddress());
		}

		SQLiteDatabase db = getWritableDatabase();
		long rowId = db.insert("destinations", null, row);
		dest.setId(rowId);
		db.close();
		return -1!=rowId;
	}
	
	public Boolean Delete(Destination dest) {
		// TODO Auto-generated method stub sqLiteDatabase.delete(MYDATABASE_TABLE, KEY_ID+"="+id, null);
		SQLiteDatabase db = getWritableDatabase();
		long rowsUpdated = db.delete("destinations", "_id = \"" + dest.getId() + "\"", null);
		db.close();
		return 1==rowsUpdated; // Andet end en opdateret række er en fejl.
	}

	/**
	 * @param dest Destination som skal opdateres i databasen.
	 * @return True hvis opdateringen gik godt.
	 */
	public Boolean UpdateDestination(Destination dest) {
		ContentValues row = new ContentValues();
		row.put("navn", dest.getName());

		if(null !=  dest.getStart()) {
			row.put("startLat", dest.getStart().getLatitude());
			row.put("startLon", dest.getStart().getLongitude());
		}
		
		if(null !=  dest.getDestination()) {
			row.put("destLat", dest.getDestination().getLatitude());
			row.put("destLon", dest.getDestination().getLongitude());
		}
		
		if (null != dest.getDestAddress() || !"".equals(dest.getDestAddress())) {
			row.put("destAddress", dest.getDestAddress());
		}
		
		if (null != dest.getStartAddress() || !"".equals(dest.getStartAddress())) {
			row.put("startAddress", dest.getStartAddress());
		}

		SQLiteDatabase db = getWritableDatabase();
		long rowsUpdated = db.update("destinations", row, "_id = \"" + dest.getId() + "\"", null);
		db.close();
		return 1==rowsUpdated; // Andet end en opdateret række er en fejl.
	}
	
	/**
	 *  Tilføjer test data til databasen.
	 */
	public void AddTestData() {
		Log.d(TAG, "AddTestData");
		SQLiteDatabase db = getWritableDatabase();
		db.execSQL("DELETE FROM destinations;");
		ContentValues row = new ContentValues();
		row.put("navn", "Herlev station");
		row.put("startLat", 55.74737);
		row.put("startLon", 12.31816);
		row.put("destLat", 55.71880);
		row.put("destLon", 12.44375);
		db.insert("destinations", null, row);

		row = new ContentValues();
		row.put("navn", "Gladsaxe vej");
		row.put("startLat", 55.71997);
		row.put("startLon", 12.44049);
		row.put("destLat", 55.74007);
		row.put("destLon", 12.48671);
		db.insert("destinations", null, row);

		row = new ContentValues();
		row.put("navn", "Målev station");
		row.put("destLat", 55.747528);
		row.put("destLon", 12.317771);
		db.insert("destinations", null, row);

		row = new ContentValues();
		row.put("navn", "Hovedbanegården");
		db.insert("destinations", null, row);

		row = new ContentValues();
		row.put("navn", "Ballerup station");
		row.put("destLat", 55.729853);
		row.put("destLon", 12.358191);
		db.insert("destinations", null, row);

		row = new ContentValues();
		row.put("navn", "Ringvejs broen");
		db.insert("destinations", null, row);

		row = new ContentValues();
		row.put("navn", "Et andet sted");
		db.insert("destinations", null, row);
		db.close();
	}

}
